{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Fermi LAT Aperture Photometry\n",
    "\n",
    "LAT light curves can be created in two different ways: either by using a likelihood analysis (see the [Likelihood](https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/likelihood_tutorial.html) and [Likelihood with Python tutorials](https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/python_tutorial.html)) or through aperture photometry.\n",
    "\n",
    "A likelihood analysis is the more rigorous approach and offers the potential to reach greater sensitivity. It also leads to more accurate flux measurement, as backgrounds can be modeled out and more detailed source models can be applied. However, aperture photometry can also be useful; it provides a model independent measure of the flux, requires fewer analysis steps, and it is less computationally demanding. It also enables the use of short time bins whereas likelihood analysis requires that time bins contain sufficient photons for analysis.\n",
    "\n",
    "It is assumed that prior to working through this tutorial, you already have a familiarity with the concepts in the [LAT Data Preparation](https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/data_preparation.html) and [Data Exploration](https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/explore_latdata.html) analysis threads. The basic steps for aperture photometry are described below. Although this is straightforward, there are several steps and so it may be convenient for them to be combined together into a script. An example of how this can be done is available in the [User Contributions](https://fermi.gsfc.nasa.gov/ssc/data/analysis/user/) area. You will also need to have the [FTOOLS](https://heasarc.gsfc.nasa.gov/ftools/ftools_menu.html) software package installed.\n",
    "\n",
    "In the example below a light curve is created centered on 3C 279. A 1-degree radius aperture is used with an energy range of 100 MeV to 200 GeV for the first 6 months of the Fermi mission.\n",
    "\n",
    "We will be using these photon and spacecraft fits files obtained from the [LAT Data Server](https://fermi.gsfc.nasa.gov/cgi-bin/ssc/LAT/LATDataQuery.cgi):\n",
    "\n",
    "```\n",
    "L1506171513514365357F56_PH00.fits\n",
    "L1506171513514365357F56_PH01.fits\n",
    "L1506171513514365357F56_SC00.fits\n",
    "```\n",
    "\n",
    "**Note**: If you have downloaded your own files from the dataserver, your numbers may vary from those in this example."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--2019-07-09 13:33:04--  https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/data/AperturePhotometry/L1506171513514365357F56_PH00.fits\n",
      "Resolving fermi.gsfc.nasa.gov (fermi.gsfc.nasa.gov)... 129.164.179.26\n",
      "Connecting to fermi.gsfc.nasa.gov (fermi.gsfc.nasa.gov)|129.164.179.26|:443... connected.\n",
      "HTTP request sent, awaiting response... 200 OK\n",
      "Length: 2617920 (2.5M) [application/fits]\n",
      "Saving to: ‘L1506171513514365357F56_PH00.fits’\n",
      "\n",
      "L150617151351436535 100%[===================>]   2.50M  --.-KB/s    in 0.04s   \n",
      "\n",
      "2019-07-09 13:33:04 (55.8 MB/s) - ‘L1506171513514365357F56_PH00.fits’ saved [2617920/2617920]\n",
      "\n",
      "--2019-07-09 13:33:05--  https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/data/AperturePhotometry/L1506171513514365357F56_PH01.fits\n",
      "Resolving fermi.gsfc.nasa.gov (fermi.gsfc.nasa.gov)... 129.164.179.26\n",
      "Connecting to fermi.gsfc.nasa.gov (fermi.gsfc.nasa.gov)|129.164.179.26|:443... connected.\n",
      "HTTP request sent, awaiting response... 200 OK\n",
      "Length: 3916800 (3.7M) [application/fits]\n",
      "Saving to: ‘L1506171513514365357F56_PH01.fits’\n",
      "\n",
      "L150617151351436535 100%[===================>]   3.74M  --.-KB/s    in 0.09s   \n",
      "\n",
      "2019-07-09 13:33:05 (42.3 MB/s) - ‘L1506171513514365357F56_PH01.fits’ saved [3916800/3916800]\n",
      "\n",
      "--2019-07-09 13:33:05--  https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/data/AperturePhotometry/L1506171513514365357F56_SC00.fits\n",
      "Resolving fermi.gsfc.nasa.gov (fermi.gsfc.nasa.gov)... 129.164.179.26\n",
      "Connecting to fermi.gsfc.nasa.gov (fermi.gsfc.nasa.gov)|129.164.179.26|:443... connected.\n",
      "HTTP request sent, awaiting response... 200 OK\n",
      "Length: 67403520 (64M) [application/fits]\n",
      "Saving to: ‘L1506171513514365357F56_SC00.fits’\n",
      "\n",
      "L150617151351436535 100%[===================>]  64.28M  40.5MB/s    in 1.6s    \n",
      "\n",
      "2019-07-09 13:33:07 (40.5 MB/s) - ‘L1506171513514365357F56_SC00.fits’ saved [67403520/67403520]\n",
      "\n"
     ]
    }
   ],
   "source": [
    "!wget https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/data/AperturePhotometry/L1506171513514365357F56_PH00.fits\n",
    "!wget https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/data/AperturePhotometry/L1506171513514365357F56_PH01.fits\n",
    "!wget https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/data/AperturePhotometry/L1506171513514365357F56_SC00.fits"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "mkdir: data: File exists\r\n"
     ]
    }
   ],
   "source": [
    "!mkdir data\n",
    "!mv *.fits ./data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "./data/L1506171513514365357F56_PH00.fits\r\n",
      "./data/L1506171513514365357F56_PH01.fits\r\n"
     ]
    }
   ],
   "source": [
    "!ls ./data/*PH*.fits > ./data/events.txt\n",
    "!cat ./data/events.txt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Combine the Data Files\n",
    "\n",
    "First, combine together the two photon files into a single file using **gtselect**.\n",
    "\n",
    "**gtselect** will be run again in a subsequent step with more selective constraints, but this shows its use for combining together multiple photon files.\n",
    "\n",
    "This approach can also be useful for combining together the weekly photon files which cover the entire sky.\n",
    "\n",
    "The file `events.txt` contains a list of the photon file names."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "WARNING: version mismatch between CFITSIO header (v3.43) and linked library (v3.41).\n",
      "\n",
      "Done.\n"
     ]
    }
   ],
   "source": [
    "!gtselect zmax=180 \\\n",
    "          emin=100 \\\n",
    "          emax=200000 \\\n",
    "          infile=@./data/events.txt \\\n",
    "          outfile=./data/tmp_19290temp1.fits \\\n",
    "          ra=180 \\\n",
    "          dec=0 \\\n",
    "          rad=180 \\\n",
    "          evclass=128 \\\n",
    "          tmin=0 \\\n",
    "          tmax=0"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, determine the start time of the photon file. Here we will use fkeypar, although other applications such as *fv* or **gtvcut** could be used as well."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "!fkeypar ./data/tmp_19290temp1.fits TSTART"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Obtain this value with **pget**:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "239557417.\r\n"
     ]
    }
   ],
   "source": [
    "!pget fkeypar value"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Determine the stop time of the photon file using **fkeypar**:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "!fkeypar ./data/tmp_19290temp1.fits TSTOP"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "and obtain the value:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "255335917.\r\n"
     ]
    }
   ],
   "source": [
    "!pget fkeypar value"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Select the desired event class\n",
    "\n",
    "An output file filtered on LAT event class is then created which is used in subsequent steps. To do that you have to run the [gtselect](https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/help/gtselect.txt) tool (see the example in the [Data Preparation](https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/data_preparation.html) tutorial.\n",
    "\n",
    "With this tool you can also select events based on the aperture, energy range, and zenith distance, and output the results to a new file. The start and stop times determined above are needed for this step. We should trim these times by about a minute on either side to allow us to barycenter the data later."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "WARNING: version mismatch between CFITSIO header (v3.43) and linked library (v3.41).\n",
      "\n",
      "Done.\n"
     ]
    }
   ],
   "source": [
    "!gtselect zmax=90 \\\n",
    "          emin=100 \\\n",
    "          emax=200000 \\\n",
    "          infile=./data/tmp_19290temp1.fits \\\n",
    "          outfile=./data/tmp_19290temp2.fits \\\n",
    "          ra=194.046527 \\\n",
    "          dec=-5.789312 \\\n",
    "          rad=1 \\\n",
    "          tmin=239557517 \\\n",
    "          tmax=255335817 \\\n",
    "          evclass=128"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For aperture photometry we select a very small aperture (`rad=1` degree), because we are not fitting the background. A tight ROI should exclude most background events and focuses on the events that are most likely to have originated from our source of interest.\n",
    "\n",
    "This data selection is significantly different from that used for likelihood analysis. Running **gtselect** generates a file with the correct events selected but without exposure corrections for that event subset."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Set the good time intervals for these selections by using **gtmktime** on the temporary file you created with **gtselect**. This uses the offset angle from the aperture and the zenith, as well as the angle of the aperture from the center of the LAT field of view to exclude times when your source is too close to the Earth's limb. It also excludes times when the source is within 5 degrees of the Sun. This can be important for times when the Sun is active.\n",
    "\n",
    "**gtmktime** creates another output file:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\r\n",
      "WARNING: version mismatch between CFITSIO header (v3.43) and linked library (v3.41).\r\n",
      "\r\n"
     ]
    }
   ],
   "source": [
    "!gtmktime scfile=./data/L1506171513514365357F56_SC00.fits \\\n",
    "          filter=\"(DATA_QUAL==1) && ABS(ROCK_ANGLE)<90 && (LAT_CONFIG==1) && (angsep(RA_ZENITH,DEC_ZENITH,194.046527,-5.789312)+1<105) && (angsep(194.046527,-5.789312,RA_SUN,DEC_SUN)>5+1) &&(angsep(194.046527,-5.789312,RA_SCZ,DEC_SCZ)<180)\" \\\n",
    "          roicut=yes \\\n",
    "          evfile=./data/tmp_19290temp2.fits \\\n",
    "          outfile=./data/tmp_19290temp3.fits"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The result is a new file ([`tmp_19290temp3.fits`](https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/data/AperturePhotometry/tmp_19290temp3.fits)) with the correct events selected as well as the proper GTIs for those selections."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Create the Light Curve\n",
    "\n",
    "Next you need to use **gtbin** to create the light curve with the desired time binning. In this case we have selected linear binning with a bin width (`dtime`) of 86400 seconds (=1 day)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "WARNING: version mismatch between CFITSIO header (v3.43) and linked library (v3.41).\n",
      "\n",
      "This is gtbin version HEAD\n"
     ]
    }
   ],
   "source": [
    "!gtbin algorithm=LC \\\n",
    "       evfile=./data/tmp_19290temp3.fits \\\n",
    "       outfile=./data/lc_3C279.fits \\\n",
    "       scfile=./data/L1506171513514365357F56_SC00.fits \\\n",
    "       tbinalg=LIN \\\n",
    "       tstart=239557517 \\\n",
    "       tstop=255335817 \\\n",
    "       dtime=86400"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This produces a binned lightcurve file: `lc_3C279.fits`.\n",
    "\n",
    "Now, you should determine the exposure for each time bin using [gtexposure](https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/help/gtexposure.txt). This is the most computationally intensive and time consuming step, as the tool generates the exposure for each time bin and writes it to a new column in your file.\n",
    "\n",
    "In the example below, a source powerlaw index of 2.1 is used. If a more accurate spectral index is known for your source, then you should use that value instead."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\r\n",
      "WARNING: version mismatch between CFITSIO header (v3.43) and linked library (v3.41).\r\n",
      "\r\n"
     ]
    }
   ],
   "source": [
    "!gtexposure infile=./data/lc_3C279.fits \\\n",
    "            scfile=./data/L1506171513514365357F56_SC00.fits \\\n",
    "            irfs=P8R3_SOURCE_V2 \\\n",
    "            srcmdl=\"none\" \\\n",
    "            specin=-2.1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If desired, the light curve can now be barycenter corrected using [gtbary](https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/help/gtbary.txt). This is only required if the time bins used are small and it is desired to investigate short timescale variability.\n",
    "\n",
    "It is important that **gtbary** is run after, and not before, the exposure correction is made."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "This is gtbary version HEAD\r\n"
     ]
    }
   ],
   "source": [
    "!gtbary evfile=./data/lc_3C279.fits \\\n",
    "        outfile=./data/lc_3C279_bary.fits \\\n",
    "        scfile=./data/L1506171513514365357F56_SC00.fits \\\n",
    "        ra=194.046527 \\\n",
    "        dec=-5.789312 \\\n",
    "        tcorrect=BARY"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**NOTE**: If you did not trim a bit of time off either end of your data set, you will get the following error here:\n",
    "\n",
    "```\n",
    "Caught St13runtime_error at the top level: Cannot get Fermi spacecraft position for 239557417 Fermi MET (TT): the time is not covered by spacecraft file L1506171513514365357F56_SC00.fits[SC_DATA]\n",
    "```\n",
    "\n",
    "This is because the spacecraft file uses 30-second gridding within your time range, and **gtbary** needs data points outside your time range to provide the reference information for the tool to use for the barycentering calculation."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You now have a light curve with counts per time bin. Note that the columns in the output file do not include a rate or a rate error column.\n",
    "\n",
    "So, in order to obtain photons/cm2/s it will be necessary to divide the COUNTS column by the EXPOSURE column. This can be accomplished, e.g. with the *fv* application or by using **ftcalc** as shown here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Dumping CFITSIO error stack:\r\n",
      "--------------------------------------------------\r\n",
      "failed to create new file (already exists?):\r\n",
      "./data/lc_3C279_rate.fits\r\n",
      "--------------------------------------------------\r\n",
      "CFITSIO error stack dump complete.\r\n",
      "CFITSIO ERROR FILE_NOT_CREATED: couldn't create the named file\r\n",
      "Task ftcalc 1.1 terminating with status 105\r\n"
     ]
    }
   ],
   "source": [
    "!ftcalc ./data/lc_3C279.fits \\\n",
    "        ./data/lc_3C279_rate.fits \\\n",
    "        RATE \\\n",
    "        'counts/exposure'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Dumping CFITSIO error stack:\r\n",
      "--------------------------------------------------\r\n",
      "failed to create new file (already exists?):\r\n",
      "./data/lc_3C279_rate_error.fits\r\n",
      "--------------------------------------------------\r\n",
      "CFITSIO error stack dump complete.\r\n",
      "CFITSIO ERROR FILE_NOT_CREATED: couldn't create the named file\r\n",
      "Task ftcalc 1.1 terminating with status 105\r\n"
     ]
    }
   ],
   "source": [
    "!ftcalc ./data/lc_3C279_rate.fits \\\n",
    "        ./data/lc_3C279_rate_error.fits \\\n",
    "        RATE_ERROR \\\n",
    "        'error/exposure'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here is an example light curve for 3C 279 obtained from aperture photometry for the first 6 months of the mission.\n",
    "\n",
    "<img src='https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/images/AperturePhotometry/3c279_lc.png'>\n",
    "\n",
    "<center>Note: The light curves obtained from aperture photometry procedure described above are NOT background subtracted. To obtain the background it will be necessary to model the sources in the region using a likelihood method. For some purposes (such as periodicity searches) background subtraction may not be necessary, and aperture photometry is appropriate.</center>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Event Weighting\n",
    "\n",
    "You may wish to use the [gtsrcprob](https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/help/gtsrcprob.txt) tool to assign probabilities to each event based on an input source model (such as the one used in the likelihood analysis). This can improve your lightcurve by increasing your acceptance radius while selecting only events that are likely to have originated from your source.\n",
    "\n",
    "To do this, first perform a [likelihood analysis](https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/likelihood_tutorial.html) for your source for the time period that interests you. This process includes calculating the diffuse responses for each event, which has already been done for the data in the `tmp_19290temp3.fits` file.\n",
    "\n",
    "The [output XML file](https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/data/AperturePhotometry/3C279_output_model.xml) from the likelihood analysis is an input for **gtsrcprob**, but should be modified so that no source name contains a space, or begins with a number. Now run **gtsrcprob** to generate probabilities that each event may originate from each of the four modeled sources (src_3C_279, src_3C_273, Galactic Diffuse, and Isotropic Diffuse). You may need to download the latest diffuse models prior to running **gtsrcprob**. All of the most up-to-date background models along with a description of the models are available [here](https://fermi.gsfc.nasa.gov/ssc/data/access/lat/BackgroundModels.html).\n",
    "\n",
    "**Note**: Since **gtsrcprob** is a function of likelihood, it should not be used as a precursor to other likelihood analyses."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--2019-07-09 13:35:55--  https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/data/AperturePhotometry/3C279_output_model.xml\n",
      "Resolving fermi.gsfc.nasa.gov (fermi.gsfc.nasa.gov)... 129.164.179.26\n",
      "Connecting to fermi.gsfc.nasa.gov (fermi.gsfc.nasa.gov)|129.164.179.26|:443... connected.\n",
      "HTTP request sent, awaiting response... 200 OK\n",
      "Length: 2468 (2.4K) [application/xml]\n",
      "Saving to: ‘3C279_output_model.xml’\n",
      "\n",
      "3C279_output_model. 100%[===================>]   2.41K  --.-KB/s    in 0s      \n",
      "\n",
      "2019-07-09 13:35:55 (18.8 MB/s) - ‘3C279_output_model.xml’ saved [2468/2468]\n",
      "\n",
      "--2019-07-09 13:35:55--  https://fermi.gsfc.nasa.gov/ssc/data/analysis/software/aux/gll_iem_v06.fits\n",
      "Resolving fermi.gsfc.nasa.gov (fermi.gsfc.nasa.gov)... 129.164.179.26\n",
      "Connecting to fermi.gsfc.nasa.gov (fermi.gsfc.nasa.gov)|129.164.179.26|:443... connected.\n",
      "HTTP request sent, awaiting response... 200 OK\n",
      "Length: 498021120 (475M) [application/fits]\n",
      "Saving to: ‘gll_iem_v06.fits’\n",
      "\n",
      "gll_iem_v06.fits    100%[===================>] 474.95M  43.6MB/s    in 14s     \n",
      "\n",
      "2019-07-09 13:36:09 (34.5 MB/s) - ‘gll_iem_v06.fits’ saved [498021120/498021120]\n",
      "\n"
     ]
    }
   ],
   "source": [
    "!wget https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/data/AperturePhotometry/3C279_output_model.xml\n",
    "!wget https://fermi.gsfc.nasa.gov/ssc/data/analysis/software/aux/gll_iem_v06.fits"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "!mv *.xml *.fits data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Run **gtdiffrsp** first."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "WARNING: version mismatch between CFITSIO header (v3.43) and linked library (v3.41).\n",
      "\n",
      "adding source gll_iem_v06\n",
      "adding source iso_P8R2_SOURCE_V6_v06\n",
      "Working on...\n",
      "./data/tmp_19290temp3.fits.....................!\n"
     ]
    }
   ],
   "source": [
    "!gtdiffrsp evfile=./data/tmp_19290temp3.fits \\\n",
    "           scfile=./data/L1506171513514365357F56_SC00.fits \\\n",
    "           srcmdl=./data/3C279_output_model.xml \\\n",
    "           irfs=P8R3_SOURCE_V2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, we run **gtsrcprob**."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\r\n",
      "WARNING: version mismatch between CFITSIO header (v3.43) and linked library (v3.41).\r\n",
      "\r\n"
     ]
    }
   ],
   "source": [
    "!gtsrcprob evfile=./data/tmp_19290temp3.fits \\\n",
    "           scfile=./data/L1506171513514365357F56_SC00.fits \\\n",
    "           outfile=./data/3C279_srcprob.fits \\\n",
    "           srcmdl=./data/3C279_output_model.xml \\\n",
    "           irfs=P8R3_SOURCE_V2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Your output file, `3C279_srcprob.fits`, now contains four new columns with the probabilities for each event. You can now filter this file and retain only events with a high probability (in this case, > 80%) of being from 3C 279."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "!ftselect ./data/3C279_srcprob.fits \\\n",
    "          ./data/3C279_srcprob_80.fits \\\n",
    "          'src_3C_279>0.8'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The resulting file can then be used as described [above](https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/aperture_photometry.html#createlc) to create a lightcurve."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
